<template>
  <el-container>
    <my-theme-card>
      <el-header>
        <el-row class="header-row">
          名称:<el-input v-model="conditions[0].value" style="width:150px;" placeholder="请输入内容" clearable />
          资源类型: <el-select v-model="conditions[1].value" placeholder="请选择" clearable>
            <el-option
              v-for="item in dir_source_type"
              :key="item.id"
              :label="item.label"
              :value="item.data"
            />
          </el-select>
          <el-button class="table-header-btn" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-col :span="1"><div class="grid-content bg-purple-light">
          <el-button class="table-header-btn" type="primary" icon="el-icon-plus" size="mini" @click="addSourceClick">新增</el-button>
        </div></el-col>
        <template>
          <el-table :data="sourceList" stripe border>
            <el-table-column prop="name" label="名称" width="180" />
            <el-table-column label="图片">
              <template slot-scope="scope">
                <div v-if="scope.row.file_type==='IMAGE'" style="width:50px;height:50px;"><img
                  :src="baseUrl+scope.row.url"
                  style="
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;"
                ></div>
                <i v-else class="el-icon-download" style="width:50px;height:50px;color:dodgerblue;text-align: center;line-height: 50px;font-size: 30px;" />
              </template>
            </el-table-column>
            <el-table-column label="资源类型" width="180">
              <template slot-scope="scope">
                {{ key_source_type[scope.row.source_type] }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="deleteClick(scope.row)">删除</el-button>
              </template>
            </el-table-column>

          </el-table>
        </template>
      </el-main>

      <el-footer>
        <div class="block">
          <el-pagination
            :current-page="page.current"
            :page-sizes="[5,10, 20, 50, 100]"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-footer>

      <el-dialog :title="form.title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" center append-to-body>
        <el-form :model="tempSource" label-width="130px" :inline="true">
          <el-form-item label="资源名称">
            <el-input v-model="tempSource.name" />
          </el-form-item>
          <el-form-item label="资源类型">
            <el-select v-model="tempSource.source_type" placeholder="请选择">
              <el-option
                v-for="item in dir_source_type"
                :key="item.id"
                :label="item.label"
                :value="item.data"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="文件路径">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="imgPreview"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadFile"
            >
              <img v-if="tempFile.type==='IMAGE'&&tempFile.url" :src="tempFile.url" class="avatar">
              <i v-else-if="tempFile.type==='BYTE'" class="avatar el-icon-check" style="font-size:30px;text-align: center;color:#61cc3c;" />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="文件名">
            <el-input v-model="tempSource.tempName" readonly />
          </el-form-item>
          <el-form-item label="文件类型">
            <el-select v-model="tempSource.file_type" placeholder="请选择" disabled>
              <el-option
                v-for="item in dir_file_type"
                :key="item.id"
                :label="item.label"
                :value="item.data"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="大小">
            <el-input v-model="size" readonly />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="uploadAndSource">确 定</el-button>
        </div>
      </el-dialog>

      <my-delete-dialog
        :show-dialog="dialogConfirmVisible"
        :row="currentSource"
        @deleteTask="deleteTask"
        @cancelTask="dialogConfirmVisible = false"
      />
    </my-theme-card>
  </el-container>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 175px;
    height: 175px;
    line-height: 175px;
    display: block;
  }
</style>

<script>
import request from '@/utils/request'
import { getBase64 } from '@/utils/file'
import { clone } from 'lodash'
export default {
  data: function() {
    return {
      conditions: [
        {
          field: 'name',
          type: 'STRING',
          value: '',
          symbol: 'LIKE'
        },
        {
          field: 'source_type',
          type: 'STRING',
          value: '',
          symbol: 'EQ'
        }
      ],
      orders: [
        { field: 'create_time', rule: 'desc' }
      ],
      baseUrl: process.env.VUE_APP_BASE_API,
      tempSource: {
        size: 0
      },
      tempFile: {
        size: 0
      },
      form: {
        title: '资源添加'
      },
      page: {
        current: 1,
        size: 5,
        total: 0
      },
      sourceList: [],
      currentSource: {},
      dialogFormVisible: false,
      dialogConfirmVisible: false
    }
  },
  computed: {
    dir_source_type: function() {
      return this.$store.state.directory.directory['source_type']
    },
    key_source_type: function() {
      const { source_type = {}} = this.$store.state.directory.directoryItem
      return source_type
    },
    dir_file_type: function() {
      return this.$store.state.directory.directory['file_type']
    },
    size: function() {
      if (((this.tempSource.size || 0) / 1024).toFixed(2) <= 100) {
        return ((this.tempSource.size || 0) / 1024).toFixed(2) + ' KB'
      }
      return ((this.tempSource.size || 0) / 1024 / 1024).toFixed(2) + ' MB'
    }
  },
  created() {
    this.directoryUpdate()
    this.query()
  },
  methods: {
    uploadFile: function(content) {
      const file = content.file
      const params = new FormData() // 创建form对象
      params.append('file', file) // 通过append向form对象添加数据//第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      params.append('fileName', this.tempSource.source_type)
      params.append('filePath', this.tempSource.source_type)
      const self = this
      const config = {
        headers: { // 添加请求头
          'Content-Type': 'multipart/form-data',
          'X-token': self.$store.state.user.token
        }
      }
      const url = process.env.VUE_APP_BASE_API + '/upload/fileUpload'
      self.$progress.start()
      this.$http.post(url, params, config).then(res => {
        this.$progress.done()
        if (res.data.result) {
          self.tempSource.url = res.data.data.url
          self.tempSource.filepath = res.data.data.filePath
          self.tempSource.size = res.data.data.size
          self.tempSource = clone(self.tempSource)
          self.addSourceTask()
          // 清除文件列表
          self.$refs.upload.clearFiles()
          // 清楚预览文件信息
          self.tempFile.type = ''
          self.tempFile.url = ''
        } else {
          self.$message.error(res.data.msg)
        }
      }).catch(() => { self.$progress.done() })
    },
    beforeAvatarUpload(file) {
      if (!this.tempSource.source_type) {
        this.$message.error('请先选择资源类型!')
        return false
      }
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 50

      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 50MB!')
      }
      if (isJPG || isPNG) {
        this.tempSource.file_type = 'IMAGE'
      } else {
        this.tempSource.file_type = 'BYTE'
      }
      return isLt2M
    },
    // 图片预览
    imgPreview: function(file, fileList) {
      const fileName = file.name
      const regex = /(.jpg|.jpeg|.gif|.png|.bmp)$/
      this.tempFile.size = file.size || 0
      this.tempSource.size = file.size || 0
      this.tempSource.tempName = fileName
      this.tempFile.tempName = fileName
      if (regex.test(fileName.toLowerCase())) {
        this.tempFile.type = 'IMAGE'
        this.tempSource.file_type = 'IMAGE'
        const self = this
        getBase64(file.raw).then(res => {
          self.tempFile.url = res
          self.tempFile = clone(self.tempFile)
        })
      } else {
        this.tempFile.type = 'BYTE'
        this.tempSource.file_type = 'BYTE'
        self.tempFile = clone(self.tempFile)
      }
    },
    directoryUpdate: function() {
      this.$store.commit('directory/setDirectory', 'file_type')
      this.$store.commit('directory/setDirectory', 'source_type')
    },
    uploadAndSource: function() {
      this.$refs.upload.submit()
    },
    // 新增资源任务
    addSourceTask: function() {
      this.$progress.start()
      request({
        url: '/bengbeng/source/add',
        method: 'post',
        data: this.tempSource
      }).then(res => {
        this.$progress.done()
        if (res.result) {
          this.tempSource = {}
          this.dialogFormVisible = false
          this.query()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      }
      ).catch(() => { this.$progress.done() })
    },
    deleteClick: function(row) {
      this.currentSource = row
      this.dialogConfirmVisible = true
    },
    deleteTask: function() {
      this.$progress.start()
      request({
        url: '/bengbeng/source/delete',
        method: 'post',
        data: this.currentSource
      }).then(res => {
        this.$progress.done()
        if (res.result) {
          this.dialogConfirmVisible = false
          this.query()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => { this.$progress.done() })
    },
    // 新增资源点击事件
    addSourceClick: function() {
      this.dialogFormVisible = true
    },
    // 每页显示数目发生变化时
    handleSizeChange: function(val) {
      this.page.size = val
      this.page.current = 1
      this.query()
    },
    // 当前页发生变化时
    handleCurrentChange: function(val) {
      this.page.current = val
      this.query()
    },
    // 搜索
    search: function() {
      this.page.current = 1
      this.query()
    },
    // 查询
    query: function() {
      this.$progress.start()
      this.page.conditions = this.conditions
      this.page.orders = this.orders
      request({
        url: '/bengbeng/source/query',
        method: 'post',
        data: this.page
      }).then(res => {
        this.$progress.done()
        if (res.result) {
          this.page.total = res.data.total
          this.sourceList = res.data.data
        }
      }).catch(() => { this.$progress.done() })
    }
  }
}
</script>
